// 操作数据库User表
import { Frequency } from '../entity/Frequency'
import { manager } from '../data-source'
import { In } from 'typeorm'
import { removePrefix } from '../../utils/index'

// 增加场次
export const addFrequency = async (data) => {
  const userRepository = manager.getRepository('User')
  const FrequencyRepository = manager.getRepository('Frequency')
  // 找到要关联的用户
  const user = await userRepository.findOne({ where: { id: data.userId } })

  if (!user) {
    return await { message: '暂无此用户' }
  }
  // 创建新的 message 实例
  const newPost = FrequencyRepository.create({
    ...data,
    user: user // 将 User 实例赋值给 Post 的 user 字段
  })

  // 保存 Post
  const res = await FrequencyRepository.save(newPost)
  return res
}

// 更新时间
export const updateFrequency = async (data) => {
  console.log(data)

  await manager.update(Frequency, { id: data.id }, data.data)
  return await true
}

// 根据场次id获取用户信息
export const getUserById = async (id) => {
  // 首先获取用户的id
  const frequency = await manager.getRepository('Frequency').findOne({
    where: { id },
    relations: ['user']
  })
  return frequency.user
}

// 根据场次id获取用户答题记录
export const getAnserById = async (id) => {
  // 首先获取用户的id
  const frequency = await manager.getRepository('Frequency').findOne({
    where: { id },
    relations: ['answer']
  })
  return frequency.answer
}
